;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.SalesDonateOut", [])
        .controller("SalesDonateOutCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", "EventBus", "MaterialService", "$stateParams", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService, EventBus, MaterialService, $stateParams) {
            $scope.activeFlag = [true, false, false, false, false];
            $scope.detailFlag = [true];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                fromSaleOrder: false
            };
            $scope.saveStateEnum = {
                save: 0,
                submit: 1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.orderPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.submitted = false;
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.condition = {};
            $scope.orderCondition = { // 新增页面列表搜索条件 
                status: 1
            };
            $scope.donateOutObj = {};
            $scope.dataList = [];
            $scope.outState = [{
                    id: 0,
                    name: "未出库"
                },
                {
                    id: 1,
                    name: "部分出库"
                },
                {
                    id: 2,
                    name: "已出库"
                },
                {
                    id: 3,
                    name: "强制结单"
                }
            ];

            $scope.orderDataList = [];
            $scope.selectedList = [];
            $scope.detailInfo = {
                sex: 1,
                locked: 0
            };

            $scope.tabFlag = {};
            $scope.stepList = {
                curStep: 0,
                list: [{
                    name: '选择销售意向单'
                }, {
                    name: '生成发货通知单'
                }]
            };
            $scope.deliveryWayList = [];
            $scope.settleTypeList = [];
            $scope.payConditionList = [];
            $scope.distributionChannelList = [];
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };
            $scope.costPriceShow = false;
            //  var isExcavatorCompany = false;


            /**
             * 导出数据接口配置
             **/
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/salesDonateOut/export"), // 导出
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/salesDonateOut/exportAll") // 导出全部
            };


            $scope.tableConfig = {
                fixedWidth: 240,
                scrollWidth: 1630,
                tableCol: [{
                        type: "",
                        name: "出库单号",
                        dataField: "salesOutBillNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "销售单号",
                        dataField: "salesBillNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "借用单号",
                        dataField: "borrowBillNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "订单类型",
                        dataField: "billTypeStr",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "clientName",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "generatePerson",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "generateDateStr",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务人员",
                        dataField: "servicePersonName",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "outboundStatusStr",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库时间",
                        dataField: "outboundDateStr",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发出仓库",
                        dataField: "outArea",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "结算状态",
                        dataField: "checkStateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "总价",
                        dataField: "totalPrice",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remark",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 200,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            $scope.tableMaterialConfig = {
                scrollWidth: 1760,
                tableCol: [{
                        type: "",
                        name: "零件编号",
                        dataField: "materialNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "默认储位",
                        dataField: "locationCode",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "订单总数",
                        dataField: "totalOrderQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "已发数量",
                        dataField: "issuedQty",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "本次发货",
                        dataField: "thisShipQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "thisShipQty",
                        sortType: "",
                        isInput: true
                    },
                    {
                        type: "",
                        name: "实际出库数量",
                        dataField: "outboundQty",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: "",
                    },
                    {
                        type: "",
                        name: "单价",
                        dataField: "singlePrice",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "singlePrice",
                        sortType: "",
                        isInput: false
                    },
                    {
                        type: "",
                        name: "实际库存",
                        dataField: "realStockQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "意向占用",
                        dataField: "intentOccupation",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        sortField: 'intentOccupation',
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发货占用",
                        dataField: "shipOccupation",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "shipOccupation",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "安全库存",
                        dataField: "safetyStock",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: 'safetyStock',
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "库存上线",
                        dataField: "onlineStock",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: 'onlineStock',
                        sortType: ""
                    },
                    {
                        type: "cost",
                        name: "成本单价",
                        dataField: "costPrice",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "costPrice",
                        sortType: "",
                        isInput: false
                    },
                    {
                        type: "cost",
                        name: "成本小计",
                        dataField: "costSubtotal",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "costSubtotal",
                        sortType: "",
                        isInput: false
                    },
                ]
            };

            $scope.outTbConf = {
                scrollWidth: 1560,
                tableCol: [{
                        type: "",
                        name: "零件编号",
                        dataField: "materialNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "订单总数",
                        dataField: "totalOrderQty",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "已发数量",
                        dataField: "issuedQty",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "本次发货",
                        dataField: "thisShipQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "thisShipQty",
                        sortType: "",
                        isInput: true
                    },
                    {
                        type: "",
                        name: "单价",
                        dataField: "singlePrice",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "singlePrice",
                        sortType: "",
                        isInput: false
                    },
                    {
                        type: "",
                        name: "实际库存",
                        dataField: "realStockQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "意向占用",
                        dataField: "intentOccupation",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        sortField: 'intentOccupation',
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发货占用",
                        dataField: "shipOccupation",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        // clickFn: "alterReport",
                        sortField: "shipOccupation",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "安全库存",
                        dataField: "safetyStock",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        // clickFn: "intentionDetail",
                        sortField: 'safetyStock',
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "库存上线",
                        dataField: "onlineStock",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        // clickFn: "deliveryDetail",
                        sortField: 'onlineStock',
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "储位",
                        dataField: "locationCode",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: "",
                        input: true,
                        inputType: "func"
                    }
                ]
            };


            $scope.salesDonateOutTbConfig = {
                fixedWidth: 60,
                scrollWidth: 1630,
                tableCol: [{
                        type: "",
                        name: "销售单号",
                        dataField: "salesBillNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "clientName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务人员",
                        dataField: "servicePersonName",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "借用单号",
                        dataField: "borrowBillNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "订单类型",
                        dataField: "billTypeStr",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请日期",
                        dataField: "createDateStr",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "收货人",
                        dataField: "consignee",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "sendQty",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "联系方式",
                        dataField: "contactPhone",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "deliveryQty",
                        sortType: "",
                        isInput: true,
                        inputType: "num"
                    },
                    {
                        type: "",
                        name: "收货地址",
                        dataField: "receiptAddress",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "receiptAddress",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "机型",
                        dataField: "model",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "使用整机编号",
                        dataField: "useMachineNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "useMachineNo",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "结算整机编号",
                        dataField: "settleMachineNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "settleMachineNo",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "原因",
                        dataField: "reason",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "reason",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "派工单号",
                        dataField: "workOrderNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "索赔单号",
                        dataField: "claimOrderNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "赠送额度类型",
                        dataField: "giveQuotaTypeStr",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remark",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "订单总价",
                        dataField: "totalOrderPrice",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调整后总价",
                        dataField: "adjustedTotalPrice",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 150,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            $scope.settleInfo = {
                donateOutObj: {},
                dataList: [],
                tableConfig: {
                    scrollWidth: 750,
                    tableCol: [{
                            name: "单据编号",
                            dataField: "billNo",
                            width: 160,
                            isShow: true,
                            type: "click",
                            clickFn: "viewDetail"
                        },
                        {
                            name: "单据类型",
                            dataField: "billTypeStr",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "单据创建时间",
                            dataField: "billDateF",
                            width: 130,
                            isShow: true
                        },
                        {
                            name: "单据总金额",
                            dataField: "totalPrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "已收金额",
                            dataField: "receivePrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "应收金额",
                            dataField: "remainPrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "本次收款金额",
                            dataField: "checkPrice",
                            width: 120,
                            isShow: true
                        }
                    ]
                }
            };

            $scope.tbMaterStyle = {
                scrollLeft: {
                    left: $scope.tableMaterialConfig.fixedWidth + "px"
                }
            };

            var materialList = [];

            var btnPermissionCode = {
                salesDonateOutAdd: window.ActionCode.salesDonateOutAdd,
                salesDonateOutEdit: window.ActionCode.salesDonateOutEdit,
                salesDonateOutDel: window.ActionCode.salesDonateOutDel,
                salesDonateOutExport: window.ActionCode.salesDonateOutExport,
                salesDonateOutPrint: window.ActionCode.salesDonateOutPrint,
                salesDonateOutOutbound: window.ActionCode.salesDonateOutOutbound,
                salesDonateOutMandatoryFinish: window.ActionCode.salesDonateOutMandatoryFinish,
                salesDonateOutSettlement: window.ActionCode.salesDonateOutSettlement,
                showCostPrice: window.ActionCode.showCostPrice, // 显示成本价
            };

            $scope.btnPermission = {
                salesDonateOutAdd: true,
                salesDonateOutEdit: true,
                salesDonateOutDel: true,
                salesDonateOutExport: true,
                salesDonateOutPrint: true,
                salesDonateOutOutbound: true,
                salesDonateOutMandatoryFinish: true,
                salesDonateOutSettlement: true,
                showCostPrice: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }


            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    }
                };
                $scope.salesDonateOutTbStyle = {
                    scrollLeft: {
                        left: $scope.salesDonateOutTbConfig.fixedWidth + "px"
                    }
                };
            };


            /* 弹出日期选择框 */
            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            /**
             * 选择日期
             **/
            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };


            /**
             * 新增页面上批量删除
             **/
            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.detailInfo.materialList.length; i < len; i++) {
                    if (!!$scope.detailInfo.materialList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.detailInfo.materialList.length - 1; i >= 0; i--) {
                        if (!!$scope.detailInfo.materialList[i].isChecked && $scope.detailInfo.materialList[i].status != 2 && $scope.detailInfo.materialList[i].status != 3) {
                            $scope.detailInfo.materialList.splice(i, 1);
                        }
                    }
                    if ($scope.detailInfo.materialList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    setTotalPrice();
                });
            };

            $scope.orderFiled = "";

            $scope.materialToSort = function (config, index) {
                if (!config[index].toSort) {
                    return;
                }
                var sortType = ybWidget.ToSort(config, index);
                var sortFiled = config[index];
                $scope.orderFiled = sortFiled.sortField;
                if (sortType == "desc") {
                    $scope.orderFiled = "-" + sortFiled.sortField;
                }
                $scope.detailInfo.materialList = $filter("orderBy")($scope.detailInfo.materialList, $scope.orderFiled);
            };



            /**
             * 新增页面上删除（单条）
             **/
            $scope.delMaterial = function (index) {
                $scope.detailInfo.materialList.splice(index, 1);
                setTotalPrice();
            };


            /**
             * 切换页面
             **/
            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.markInfo.allCheckedMaterial = false;
                $scope.submitted = false;
                switch (index) {
                    case 0: // 列表
                        initData();
                        break;
                    case 1: // 新增
                        break;
                    case 2: // 查看详情
                        break;
                    case 3: // 操作出库
                        break;
                    case 4: // 操作结算
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {};
                $scope.stepList.curStep = 0;
                $scope.deliveryWayList = [];
                $scope.settleTypeList = [];
                $scope.payConditionList = [];
                $scope.detailFlag = [true];
                $scope.markInfo.fromSaleDonateOut = false; // 返回上级页面
                materialList = [];
            }

            function getOrderDataList(curPage) {
                $scope.markInfo.allCheckedMaterial = false;
                var service = "device";
                var reqUrl = "/salesDonateOut/salasOutBillList";
                var param = {};
                param.pageSize = $scope.orderPageInfo.pageSize;
                if (!!curPage) {
                    $scope.orderPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.orderPageInfo.curPage;
                param.filters = angular.copy($scope.orderCondition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    angular.forEach(resp.value.list, function (item) {
                        item.createDateStr = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.statusStr = $filter("Status")(item.status);
                        item.billTypeStr = $filter("BillTypeStatus")(item.billType);
                        item.giveQuotaTypeStr = $filter("GiveQuotaTypeStatus")(item.giveQuotaType);
                    });
                    $scope.orderPageInfo.totalRows = resp.value.total;
                    $scope.orderPageInfo.totalPages = resp.value.pages;
                    $scope.orderDataList = resp.value.list;
                });
            }


            /**
             * 配置表格列
             **/
            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };


            /**
             * 加载销售赠送出库列表
             **/
            function getDataList(curPage) {
                $scope.markInfo.allCheckedBill = false;
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/salesDonateOut/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    // 列表中数据格式的转换
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.billTypeStr = $filter("BillTypeStatus")(item.billType);
                        item.checkStateShow = $filter("ProgressStatus")(item.checkState, "checkState");
                        item.outboundStatusStr = $filter("ProgressStatus")(item.outboundStatus, "outDepot");
                        item.outboundDateStr = $filter("YbDate")(item.outboundDate, 'yyyy-MM-dd HH:mm:ss');
                        item.generateDateStr = $filter("YbDate")(item.generateDate, 'yyyy-MM-dd HH:mm:ss');
                    });

                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }


            /**
             * 新建页面中选择列表上某条字段跳转到新建页面
             **/
            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    case "alterReport":
                        alterReport(item);
                        break;
                    case "intentionDetail":
                        intentionDetail(item);
                        break;
                    case "deliveryDetail":
                        deliveryDetail(item);
                        break;
                    default:
                        break;
                }
            };

            function intentionDetail(item) {
                var param = {
                    materialsNo: item.materialsNo
                };
                ybWidget.IntentionDetail(param);
            }

            function deliveryDetail(item) {
                var param = {
                    materialsNo: item.materialsNo,
                    warehouseCode: $scope.detailInfo.headerInfo.outLocation
                };
                if ($scope.activeFlag[4]) { // 操作出库
                    param.billNo = $scope.detailInfo.headerInfo.deliveryNo;
                }
                ybWidget.DeliveryDetail(param);
            }

            function alterReport(item) {
                var param = {
                    materialsNo: item.materialsNo
                };
                ybWidget.StorageReport(param);
            }



            /**
             * 按条件搜索
             **/
            $scope.orderSearch = function () {
                getOrderDataList();
            };



            /**
             * 新增页面点击列表上某条的选择
             **/
            $scope.orderSelectSingle = function (item) {
                $scope.markInfo.allCheckedMaterial = false;
                ybHttp.Get('device', '/salesDonateOut/itemBySaleBillNo', {
                    salesNo: item.salesBillNo
                }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    // 初始化零件的checkbox
                    angular.forEach(resp.value.materialList, function (item) {
                        item.isChecked = false;
                    });
                    $scope.detailInfo = resp.value;
                    $scope.detailInfo.headerInfo = {};
                    $scope.detailInfo.headerInfo.salesBillNo = item.salesBillNo;
                    $scope.detailInfo.headerInfo.clientName = item.clientName;
                    $scope.detailInfo.headerInfo.useMachineNo = item.useMachineNo;
                    $scope.detailInfo.headerInfo.servicePersonName = item.servicePersonName;

                    $scope.detailInfo.headerInfo.createDateStr = item.createDateStr;
                    $scope.detailInfo.headerInfo.createDate = item.createDate;

                    $scope.detailInfo.headerInfo.billType = item.billType;
                    $scope.detailInfo.headerInfo.billTypeStr = item.billTypeStr;
                    $scope.detailInfo.headerInfo.borrowBillNo = item.borrowBillNo;
                    $scope.detailInfo.headerInfo.consignee = item.consignee;
                    $scope.detailInfo.headerInfo.contactPhone = item.contactPhone;
                    $scope.detailInfo.headerInfo.receiptAddress = item.receiptAddress;

                    $scope.detailInfo.headerInfo.outboundDateStr = $filter("YbDate")($scope.detailInfo.headerInfo.outboundDate, 'yyyy-MM-dd HH:mm:ss');

                    $scope.detailInfo.headerInfo.generateDateStr = $filter("YbDate")(new Date(), 'yyyy-MM-dd HH:mm:ss');

                    setTotalPrice();
                    // $scope.detailInfo.headerInfo.totalOrderPrice = item.totalOrderPrice;

                    materialList = angular.copy($scope.detailInfo.materialList);
                    $scope.stepList.curStep = 1;
                });
            };
            $scope.prevStep = function () {
                $scope.stepList.curStep = 0;
            };

            /* 列表排序 */
            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };


            /* 勾选列表数据 */
            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };


            /* 点击刷新按钮，重新加载列表 */
            $scope.search = function (curpage) {
                getDataList(curpage);
            };


            /* 重置查询条件 */
            $scope.reset = function () {
                $scope.condition = {};
            };



            /************  选择数据开始 ************ */
            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };
            /************  选择数据结束 ************ */


            /**
             * 新增页面上方条件展开收起
             **/
            $scope.switchDetailBar = function (index) {
                $scope.detailFlag[index] = !$scope.detailFlag[index];
            };


            /**
             * 新增
             **/
            $scope.addData = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                getOrderDataList();
                $scope.changeTab(1);
            };



            /**
             * 获取价格通用方法
             **/
            function getPrice(price) {
                var maxPrice = $scope.settleInfo.donateOutObj.maxPrice;
                // 价格不能大于最大值
                var result = parseFloat(price || 0);
                return result > maxPrice ? maxPrice : result;
            }


            /**
             * 修改预付款扣减价格
             **/
            $scope.changePrePayMoney = function () {
                var advancePayPrice = Number($scope.settleInfo.donateOutObj.advancePayPrice) || 0;
                var prePayPrice = Number($scope.settleInfo.donateOutObj.prePayPrice) || 0;
                // 如果预收款扣减大于客户的预收款额度 则取额度的值
                if (prePayPrice > advancePayPrice) {
                    $scope.settleInfo.donateOutObj.prePayPrice = advancePayPrice;
                }
                $scope.changeMoney();
            };


            /**
             * 修改车辆额度价格
             **/
            $scope.changeVehicleQuota = function () {
                var vehiclePrice = Number($scope.settleInfo.donateOutObj.vehiclePrice) || 0;
                var useVehicleQuota = Number($scope.settleInfo.donateOutObj.useVehicleQuota) || 0;
                // 如果预收款扣减大于客户的预收款额度 则取额度的值
                if (vehiclePrice > useVehicleQuota) {
                    $scope.settleInfo.donateOutObj.vehiclePrice = useVehicleQuota;
                }
                $scope.changeMoney();
            };


            /**
             * 修改价格后价格联动
             **/
            $scope.changeMoney = function (type) {
                var totalPrice = $scope.settleInfo.donateOutObj.totalPrice; // 销售总额
                var discountPrice = getPrice($scope.settleInfo.donateOutObj.discountPrice); // 优惠金额
                var prePayPrice = getPrice($scope.settleInfo.donateOutObj.prePayPrice); // 预付款
                var vehiclePrice = getPrice($scope.settleInfo.donateOutObj.vehiclePrice); // 车辆额度
                var cashMoney = getPrice($scope.settleInfo.donateOutObj.cashMoney); // 结算金额
                var restPrice = ybWidget.MultiMinus(totalPrice, discountPrice, prePayPrice, vehiclePrice);
                if (type === 'cash') {
                    $scope.settleInfo.donateOutObj.debt = ybWidget.MultiMinus(restPrice, cashMoney);
                    $scope.settleInfo.dataList[0].checkPrice = ybWidget.MultiPlus(discountPrice, cashMoney, prePayPrice, vehiclePrice);
                    return;
                }
                $scope.settleInfo.donateOutObj.cashMoney = restPrice <= 0 ? 0 : restPrice;
                $scope.settleInfo.dataList[0].checkPrice = ybWidget.MultiPlus(discountPrice, prePayPrice, vehiclePrice, $scope.settleInfo.donateOutObj.cashMoney);
                $scope.settleInfo.donateOutObj.debt = restPrice >= 0 ? 0 : restPrice;
            };



            /**
             * 提交结算
             **/
            $scope.saveAddReceipt = function (isValid) {
                if (!isValid || $scope.settleInfo.donateOutObj.debt < 0) {
                    $scope.submitted = true;
                    return;
                }
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                var service = "device";
                var reqUrl = "/check/add";
                param.headerInfo.discountPrice = $scope.settleInfo.donateOutObj.discountPrice || 0;
                param.headerInfo.checkType = 0;
                param.headerInfo.supplierOrgId = $scope.curOrgId;
                param.headerInfo.supplierOrgName = $scope.curOrg.companyName;
                param.headerInfo.purchaseOrgId = $scope.settleInfo.donateOutObj.orgId;
                param.headerInfo.purchaseOrgName = $scope.settleInfo.donateOutObj.clientName;
                param.headerInfo.operatorId = $scope.settleInfo.donateOutObj.operatorId;
                param.headerInfo.operatorName = $scope.settleInfo.donateOutObj.operatorName;
                param.headerInfo.note = $scope.settleInfo.donateOutObj.note;
                param.headerInfo.settleType = 0;
                param.headerInfo.isDealer = 1;
                param.headerInfo.totalPrice = $scope.settleInfo.donateOutObj.totalPrice;
                param.headerInfo.advancePayPrice = $scope.settleInfo.donateOutObj.prePayPrice;
                param.headerInfo.useVehicleQuota = $scope.settleInfo.donateOutObj.vehiclePrice;
                param.headerInfo.realPrice = +$scope.settleInfo.donateOutObj.cashMoney;

                angular.forEach($scope.settleInfo.dataList, function (item) {
                    param.detailList.push({
                        arapDetailId: item.id,
                        billDate: item.billDate,
                        billNo: item.billNo,
                        billId: item.billId,
                        billSingle: item.billSingle,
                        checkPrice: item.checkPrice,
                        totalPrice: item.totalPrice,
                        receivePrice: item.remainPrice
                    });
                });

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                    $scope.changeTab(0);
                });
            };


            /**
             * 去结算页面
             **/
            $scope.goSettlement = function (item) {
                var nowDate = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
                $scope.settleInfo.viewDetailItem = item;
                $scope.settleInfo.donateOutObj = {
                    createDate: nowDate,
                    orgId: item.purchaseOrgId,
                    clientName: item.clientName,
                    billType: item.billType,
                    totalPrice: item.totalDiscountPrice,
                    maxPrice: item.totalDiscountPrice,
                    cashMoney: item.totalDiscountPrice
                };
                getReceiptTableList(item.salesOutBillNo);
                getClientPrepay(item.salesBillNo);
                $scope.changeTab(4);
            };


            /**
             * 过账：wangcan
             **/
            $scope.goTransfer = function (item) {
                // 传什么参数去调用接口?
                // var service = "device",
                //     reqUrl = "/arap/detailList",
                //     param = {
                //         filters: {
                //             type: 0,
                //             isSettle: 0,
                //             isAll: 1,
                //             billNo: billNo
                //         }
                //     };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                    $scope.changeTab(0);
                });
            };




            /**
             * 获取收款单据列表
             **/
            function getReceiptTableList(billNo) {
                var service = "device",
                    reqUrl = "/arap/detailList",
                    param = {
                        filters: {
                            type: 0,
                            isSettle: 0,
                            isAll: 1,
                            billNo: billNo
                        }
                    };
                ybHttp.Post(service, reqUrl, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(res.value.list, function (item) {
                        item.billTypeStr = $filter("BillTypeStatus")(item.saleBillType);
                        item.billDateF = $filter("YbDate")(item.billDate, "yyyy-MM-dd HH:mm:ss");
                        item.checkPrice = item.remainPrice;
                    });
                    $scope.settleInfo.dataList = res.value.list;
                });
            }



            /**
             * 获取用户预存款 和 车辆额度
             **/
            function getClientPrepay(salesBillNo) {
                var url = '/arap/getPrepPayPrice';
                var params = {
                    salesBillNo: salesBillNo
                };
                ybHttp.Get('device', url, params).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    $scope.settleInfo.donateOutObj.advancePayPrice = res.value.advancePayPrice || 0;
                    $scope.settleInfo.donateOutObj.useVehicleQuota = res.value.useVehicleQuota || 0;
                })
            }



            /**
             * 选择经办人
             **/
            $scope.selectOperator = function () {
                var param = {
                    name: "经办人",
                    type: "agent",
                    supplierOrgId: $scope.curOrgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.settleInfo.donateOutObj.operatorId = data.userId;
                    $scope.settleInfo.donateOutObj.operatorName = data.name;
                })
            };


            /**
             * 选择仓库
             **/
            $scope.selectWarehouse = function () {
                ybWidget.WarehouseSelector().then(function (data) {
                    angular.forEach(materialList, function (item) {
                        item.isChecked = false;
                        // 选择库区后 展示零件的默认储位
                        var locationList = item.stockLocationList || [];
                        for (var j = 0; j < locationList.length; j++) {
                            if (data.warehouseCode == locationList[j].warehouseCode) {
                                item.locationCode = locationList[j].locationCode;
                                break;
                            }
                        }
                    });
                    $scope.markInfo.allCheckedMaterial = false;
                    $scope.detailInfo.headerInfo.outArea = data.warehouseCode;
                    $scope.detailInfo.materialList = angular.copy(materialList);
                    // 获取剩余库存
                    findDeliveryNum().then(function () {
                        // 把实际库存是0的无聊过滤掉
                        //filterMaterial();
                    });
                })
            };


            /**
             * 清除仓库
             **/
            $scope.clearWarehouse = function () {
                $scope.detailInfo.headerInfo.outLocation = "";
                $scope.detailInfo.headerInfo.outArea = "";
                $scope.detailInfo.headerInfo.sapOutArea = "";
                angular.forEach(materialList, function (item) {
                    item.stockLocation = "";
                    // 清除仓库后 同时清除 默认储位
                    item.locationCode = "";
                });
                $scope.detailInfo.materialList = materialList;
                angular.forEach($scope.detailInfo.materialList, function (item) {
                    item.deliveryNum = item.oldDeliveryNum;
                    item.enableNum = item.oldEnableNum;
                });
            };


            /**
             * 获取剩余库存
             **/
            function findDeliveryNum() {
                var service = "device";
                var reqUrl = "/salesBill/findDeliveryNum";
                var param = {};
                param.salesBillNo = $scope.detailInfo.headerInfo.salesBillNo;
                param.warehouseCode = $scope.detailInfo.headerInfo.outArea;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    if (!resp.value) {
                        return;
                    }
                    // 将实际库存和发货占用赋值给detailinfo对象
                    angular.forEach($scope.detailInfo.materialList, function (item) {
                        angular.forEach(resp.value, function (itemDetail) {
                            if (item.materialNo === itemDetail.materialNo) {
                                item.realStockQty = itemDetail.enableNum;
                                item.shipOccupation = itemDetail.deliveryNum;
                            }
                        });

                        // 判断本次发货是不是大于订单总数或者实际库存
                        $scope.checkQty(item);
                    });
                });
            }

            function filterMaterial() {
                $scope.detailInfo.materialList = $scope.detailInfo.materialList.filter(function (item) {
                    return item.realStockQty > 0;
                });
            }

            function getDetail(billId) {
                var service = "device";
                var reqUrl = "/salesDonateOut/item";
                var param = {};
                param.id = billId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            function viewDetail(item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.detailInfo = data;

                    $scope.detailInfo.headerInfo.generateDateStr = $filter("YbDate")($scope.detailInfo.headerInfo.generateDate, 'yyyy-MM-dd HH:mm:ss');
                    $scope.detailInfo.headerInfo.checkStateShow = $filter("ProgressStatus")($scope.detailInfo.headerInfo.checkState, "checkState");
                    $scope.detailInfo.headerInfo.outboundStatusStr = $filter("ProgressStatus")($scope.detailInfo.headerInfo.outboundStatus, "outDepot")
                    $scope.detailInfo.headerInfo.outboundDateStr = $filter("YbDate")($scope.detailInfo.headerInfo.outboundDate, 'yyyy-MM-dd HH:mm:ss');

                    $scope.changeTab(2);
                });
            }



            /** 
             *打印
             **/
            $scope.printSingle = function (item) {
                var id = item.id;
                var billIds = [];
                billIds.push(id);
                var param = {
                    billId: billIds,
                    printType: "SalesDonateOut"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };



            /**
             * 列表页上方批量打印
             **/
            $scope.batchPrint = function () {
                var param = {
                    billId: [],
                    printType: "SalesDonateOut"
                };
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        param.billId.push($scope.dataList[i].id);
                    }
                }
                if (param.billId.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }
                ybWidget.SetIsPrintOrPreview(param);
            };



            /**
             * 出库
             **/
            $scope.outbound = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.detailInfo = data;
                    $scope.detailInfo.headerInfo.checkStateShow = $filter("ProgressStatus")($scope.detailInfo.headerInfo.checkState, "checkState");
                    $scope.detailInfo.headerInfo.outboundStatusStr = $filter("ProgressStatus")($scope.detailInfo.headerInfo.outboundStatus, "outDepot")
                    $scope.detailInfo.headerInfo.outboundDateStr = $filter("YbDate")($scope.detailInfo.headerInfo.outboundDate, 'yyyy-MM-dd HH:mm:ss');
                    $scope.changeTab(3);
                });
            };


            /**
             * 编辑
             **/
            $scope.editData = function (item) {
                $scope.markInfo.allCheckedMaterial = false;
                var service = "device";
                var reqUrl = "/salesDonateOut/item";
                var param = {};
                param.id = item.id;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1];
                    $scope.changeTab(1);
                    $scope.stepList.curStep = 1;
                    $scope.detailInfo = resp.value;
                    $scope.detailInfo.headerInfo.billTypeStr = $filter("BillTypeStatus")($scope.detailInfo.headerInfo.billType);
                    $scope.detailInfo.headerInfo.generateDateStr = $filter("YbDate")($scope.detailInfo.headerInfo.generateDate, 'yyyy-MM-dd HH:mm:ss');
                    setTotalPrice();
                });
            };


            /**
             * 列表页上方删除
             **/
            $scope.delData = function (delType, Id) {
                var service = "device";
                var reqUrl = "/salesDonateOut/delete";
                var param = {};
                param.Ids = [];

                if (delType === "single") {
                    param.Ids.push(Id);
                }
                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked && $scope.dataList[i].outboundStatus === 0 && $scope.dataList[i].checkState === 0) {
                            param.Ids.push($scope.dataList[i].id);
                        }
                    }
                }
                if (param.Ids.length === 0) {
                    ybWidget.ShowMessage('请正确选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param.Ids).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                }, function () {})
            };


            /**
             * 结单
             **/
            $scope.mandatoryFinish = function (detailInfo, id, materialsNo) {
                ybWidget.ShowMessage("确定要结单吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/salesDonateOut/manualFinish";
                    var param = {
                        billNo: detailInfo.salesOutBillNo, // 出库单号
                        materialsNo: materialsNo ? materialsNo : null
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!id) {
                            getDetail(id).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                $scope.detailInfo = data;
                                $scope.detailInfo.headerInfo.generateDateStr = $filter("YbDate")($scope.detailInfo.headerInfo.generateDate, 'yyyy-MM-dd HH:mm:ss');
                                $scope.detailInfo.headerInfo.checkStateShow = $filter("ProgressStatus")($scope.detailInfo.headerInfo.checkState, "checkState");
                                $scope.detailInfo.headerInfo.outboundStatusStr = $filter("ProgressStatus")($scope.detailInfo.headerInfo.outboundStatus, "outDepot")
                                $scope.detailInfo.headerInfo.outboundDateStr = $filter("YbDate")($scope.detailInfo.headerInfo.outboundDate, 'yyyy-MM-dd HH:mm:ss');

                            });
                        }
                        getDataList();
                    });
                }, function () {});
            };


            // function checkNumValid() {
            //     var valid = true;
            //     angular.forEach($scope.detailInfo.materialList, function (item) {
            //         if (!item.deliveryQty || item.deliveryQty == "0" || parseFloat(item.deliveryQty) <= 0) {
            //             valid = false;
            //             item.qtyErr = true;
            //             item.qtyErrMsg = "发货数量不能为空和0";
            //         }
            //         if (item.deliveryQty > item.deliveryMax) {
            //             valid = false;
            //             item.qtyErr = true;
            //             item.qtyErrMsg = "发货数量不能超过允许数量";
            //         }
            //     });
            //     return valid;
            // }

            // $scope.clickValue = false;
            // $scope.submitData = function (isValid) {
            //     if (!isValid) {
            //         $scope.submitted = true;
            //         return;
            //     }
            //     if ($scope.clickValue) {
            //         return;
            //     }
            //     $scope.clickValue = true;
            //     if ($scope.detailInfo.materialList.length === 0) {
            //         $scope.clickValue = false;
            //         ybWidget.ShowToaster('error', '请选择零件');
            //         return;
            //     }
            //     if (!checkNumValid()) {
            //         $scope.clickValue = false;
            //         return;
            //     }
            //     var msg = checkPrice();
            //     if (msg !== '0') {
            //         $scope.clickValue = false;
            //         ybWidget.ShowToaster('error', msg);
            //         return;
            //     }

            //     var service = "device";
            //     var reqUrl = "/deliveryNote/submit";
            //     var param = {};
            //     param = $scope.detailInfo;
            //     ybHttp.Post(service, reqUrl, param).then(function (resp) {
            //         if (resp.code !== 0) {
            //             ybWidget.ShowMessage(resp, MESG_TYPE.Error);
            //             $scope.clickValue = false;
            //             return;
            //         }
            //         ybWidget.ShowToaster('success', '操作成功');
            //         $scope.changeTab(0);
            //         getDataList();
            //         $scope.markInfo.allCheckedBill = false;
            //         $scope.markInfo.allCheckedMaterial = false;
            //         $scope.clickValue = false;
            //     });
            // };


            /* 发货数量错误，报错 */
            $scope.showQtyTip = function (item) {
                if (!!item.qtyStockErr) {
                    item.showStockErr = true;
                }
            };

            $scope.hideQtyTip = function (item) {
                item.showStockErr = false;
            };


            /**
             * 设置头部信息中的订单总价
             **/
            function setTotalPrice() {
                var totalPrice = 0;
                var costTotal = 0; // 成本总价
                angular.forEach($scope.detailInfo.materialList, function (item) {
                    // 一条零件的总价，单价乘以本次发货数量
                    var itemTotlePrice = $filter("decimalCover")(ybWidget.Times(item.singlePrice || 0, item.thisShipQty), 2);
                    totalPrice = ybWidget.Plus(totalPrice, parseFloat(itemTotlePrice));
                    costTotal = ybWidget.Plus(costTotal, parseFloat(item.costSubtotal || 0));
                });
                $scope.detailInfo.headerInfo.totalOrderPrice = $filter("decimalCover")(totalPrice, 2);
                $scope.detailInfo.headerInfo.costTotal = $filter("decimalCover")(costTotal, 2);
            }

            $scope.checkQty = function (item) {
                item.qtyErr = false;
                if (!item.thisShipQty || item.thisShipQty == "0" || parseFloat(item.thisShipQty) <= 0) {
                    item.qtyErr = true;
                    item.qtyErrMsg = "不能为空和0";
                    return;
                }
                //本次发货数量不能大于 （订单总数-已发数量）的数量，或者不能大于实际库存
                var shipMax = item.totalOrderQty - item.issuedQty;
                if (item.thisShipQty > shipMax) {
                    item.qtyErr = true;
                    item.qtyErrMsg = "不能大于本次发货数量";
                    return;
                }
                // 根据成本价计算成本小计
                if (item.costPrice) {
                    item.costSubtotal = $filter("decimalCover")(ybWidget.Times(parseFloat(item.thisShipQty), item.costPrice), 2);
                }
                setTotalPrice();
            };



            /**
             * 新增页面保存或者提交
             **/
            $scope.saveData = function (isValid, status) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                // 如果零件列表里面有错误则不可以删除
                for (var i = 0, len = $scope.detailInfo.materialList.length; i < len; i++) {
                    if (!!$scope.detailInfo.materialList[i].qtyErr) {
                        return;
                    }
                }

                if ($scope.detailInfo.materialList.length === 0) {
                    ybWidget.ShowMessage('必须有零件');
                    return;
                }
                var service = "device";
                var reqUrl = "/salesDonateOut/add";
                var param = angular.copy($scope.detailInfo);
                param.status = status;
                param.headerInfo.totalPrice = param.headerInfo.totalOrderPrice;
                param.headerInfo.generateDate = new Date();
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        $scope.clickValue = false;
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                    $scope.markInfo.allCheckedBill = false;
                    $scope.markInfo.allCheckedMaterial = false;
                });
            };


            /**
             * 选择储位（单选）
             **/
            $scope.selDepot = function (item) {
                var param = {
                    warehouseCode: $scope.detailInfo.headerInfo.outArea
                };
                ybWidget.DepotSelector(param).then(function (data) {
                    item.warehouseCode = data.warehouseCode;
                    item.areaCode = data.areaCode;
                    item.locationCode = data.locationCode;
                })
            };



            /**
             * 批量选择储位
             **/
            $scope.multiSelDepot = function () {
                var warehouseCode = $scope.detailInfo.headerInfo.outArea;
                var list = $scope.detailInfo.materialList;
                MaterialService.multiSelDepot(warehouseCode, list);
            };


            /**
             * 取消选择储位
             **/
            $scope.clearDepot = function (item) {
                item.warehouseCode = "";
                item.areaCode = "";
                item.locationCode = "";
            };


            /**
             * 确认出库
             **/
            $scope.outboundSubmit = function () {
                var haslocationCode = $scope.detailInfo.materialList.every(function (item) {
                    return !!item.locationCode
                });
                if (!haslocationCode) {
                    ybWidget.ShowMessage("请选择储位", MESG_TYPE.Error);
                    return;
                }
                var service = "device";
                var reqUrl = "/warehouseDeliveryRecord/receive";
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                param.headerInfo.businessOrder = $scope.detailInfo.headerInfo.salesOutBillNo;
                angular.forEach($scope.detailInfo.materialList, function (item) {
                    var listRow = {};
                    listRow.materialNo = item.materialNo;
                    listRow.warehouseCode = item.warehouseCode;
                    listRow.areaCode = item.areaCode;
                    listRow.locationCode = item.locationCode;
                    param.detailList.push(listRow);
                });
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };


            /**
             * 取消
             **/
            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            (function () {
                // 提交销售单自动生成销售出库单
                if ($stateParams.billId) {
                    ybHttp.Get('device', '/salesBill/detail', {
                        id: $stateParams.billId
                    }).then(function (res) {
                        if (res.code !== 0) {
                            ybWidget.ShowMessage(res, MESG_TYPE.Error);
                            return;
                        }
                        res.value.salesBillVO.createDateStr = $filter("YbDate")(res.value.salesBillVO.createDate, 'yyyy-MM-dd HH:mm:ss');
                        res.value.salesBillVO.statusStr = $filter("Status")(res.value.salesBillVO.status);
                        res.value.salesBillVO.billTypeStr = $filter("BillTypeStatus")(res.value.salesBillVO.billType);
                        res.value.salesBillVO.giveQuotaTypeStr = $filter("GiveQuotaTypeStatus")(res.value.salesBillVO.giveQuotaType);
                        $scope.orderSelectSingle(res.value.salesBillVO);
                        $scope.tabFlag.type = 0;
                        $scope.tabFlag.name = tabFlag[0];
                        $scope.markInfo.fromSaleDonateOut = true; // 返回上级页面
                        $scope.changeTab(1);
                    });
                }
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);